package com.adee.gulimall.product.web;

import com.adee.gulimall.product.entity.CategoryEntity;
import com.adee.gulimall.product.service.CategoryService;
import com.adee.gulimall.product.vo.CategoryJson2Object;
import com.adee.gulimall.product.vo.CategoryJson3Object;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @GetMapping(value = {"/", "/index.html"})
    public String indexPage(Model model) {
        List<CategoryEntity> list = categoryService.getLevel1Categories();
        model.addAttribute("categories", list);
        return "index";
    }


    @GetMapping("/index/json/catalog.json")
    @ResponseBody
    public Map<String, Object> categoryJson(){
        log.info("");
        log.info("========>>>");
        long t0 = System.currentTimeMillis();
        List<CategoryEntity> list = categoryService.listWithTree();
        long t1 = System.currentTimeMillis();
        log.info("categoryService.listWithTree(): {}", t1-t0);
        Map<String, Object> map = new HashMap<>();
        list.forEach( c -> {
            List<CategoryJson2Object> catalog2JsonList = new ArrayList<>();
            map.put(Long.toString(c.getCatId()), catalog2JsonList);
            List<CategoryEntity> children2 = c.getChildren();
            if(children2 != null) {
                children2.forEach(c2 -> {
                    List<CategoryJson3Object> catalog3JsonList = new ArrayList<>();
                    CategoryJson2Object categoryJson2Object =
                            new CategoryJson2Object(
                                    Long.toString(c2.getCatId()),
                                    c2.getName(),
                                    Long.toString(c2.getParentCid()),
                                    catalog3JsonList);
                    catalog2JsonList.add(categoryJson2Object);
                    List<CategoryEntity> children3 = c2.getChildren();
                    if(children3 != null) {
                        children3.forEach(c3 -> {
                            CategoryJson3Object categoryJson3Object = new CategoryJson3Object(
                                    Long.toString(c3.getCatId()),
                                    c3.getName(),
                                    Long.toString(c3.getParentCid()));
                            catalog3JsonList.add(categoryJson3Object);
                        });
                    }
                });
            }

        });
        long t2 = System.currentTimeMillis();
        log.info("list.forEach: {}", t2-t1);

        return map;
    }

    // 简单服务，不涉及到后后端，即redis、mysql，用于压测：nginx -> gateway -> 简单服务
    @GetMapping("/product/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    @GetMapping(value = {"/csrf.html"})
    public String csrf(HttpServletRequest req, HttpServletResponse resp) {

        Cookie c = new Cookie("hello", "123");
        c.setPath("/csrf");
        resp.addCookie(c);
        return "csrf";
    }

    @GetMapping(value = {"/hello/test/csrf.html"})
    public String helloTestCsrf(HttpServletRequest req, HttpServletResponse resp) {

        Cookie c = new Cookie("helloTestCsrf", "456");
        // 浏览器检测到与发起请求所在的页面的域名不同，会将该cookie忽略，所以要设置为父级域名，或者不设置，默认为当前域名
        c.setDomain("hello.search.gmall.com");
        // 父path的页面不能访问到子path的cookie，但是子path的页面能访问到父path的cookie
        // c.setPath("/"); // 允许向上设置，该域名下所有页面都能访问到该cookie
        // 也允许向下设置，但只有子path的页面能访问到该cookie，即/hello/test/abc及其子路径的页面能访问到该cookie
        c.setPath("/hello/test/abc");
        resp.addCookie(c);
        return "csrf";
    }

    @GetMapping(value = {"/hello/test/abc/csrf.html"})
    public String helloTestCsrfAbc(HttpServletRequest req, HttpServletResponse resp) {

        return "csrf";
    }

    @GetMapping(value = {"/logout.html"})
    public String logout(HttpServletRequest req, HttpServletResponse resp) {

        Cookie c = new Cookie("hello", "123");
        c.setMaxAge(0);
        resp.addCookie(c);

        return "csrf";
    }

}
